/*
 *
 * FileName: ConfigServer.java
 * Author:   wx:fdzhangc
 * Date:     2021/11/24 16:35
 * Description: //模块目的、功能描述
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名    修改时间    版本号       描述
 */
package com.zhangc.zcscm.simple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class ConfigServer extends ConnectWatcher {
    private String rootPath = "/config";

    public ConfigServer() {
        this.connect();
    }

    //写入配置信息
    public void write(String key, String value) {
        try {
            Stat stat = this.zooKeeper.exists(rootPath + "/" + key, false);
            if (stat != null) {
                this.zooKeeper.setData(rootPath + "/" + key, value.getBytes(), -1);
            } else {
                this.zooKeeper.create(rootPath + "/" + key, value.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Map<String, String> getAllConfig() {
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
            List<String> paths = this.zooKeeper.getChildren(rootPath, false);
            for (String path : paths) {
                System.out.println(path);
                String value = new String(this.zooKeeper.getData(rootPath + "/" + path, false, null));
                resultMap.put(path, value);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    public void createRoot() {
        try {
            this.zooKeeper.create("/config", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String readConfig(String key, Watcher watcher) {
        byte[] bytes = null;
        try {
            bytes = this.zooKeeper.getData(rootPath + "/" + key, watcher, null);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (bytes == null) {
            return null;
        }
        return new String(bytes);
    }
}
